package main

import (
    "fmt"
    "github.com/fsnotify/fsnotify"
    "../dmap"
    "os"
)


func main() {
    watcher, err := fsnotify.NewWatcher()
    if err != nil {
        fmt.Println(err)
        os.Exit(1)
    }
    defer watcher.Close()
    localNotifyHandler := func(dirs []string, dfiles []string, cfiles []string) error {
        for _, d := range dirs {
            if err := watcher.Add(d); err != nil {
                return err
            }
        }
        return nil
    }
    rn,err:=dmap.NewDistributeMap("nginx/photoV2","0","","",[]string{"http://127.0.0.1:3379","http://127.0.0.1:3381","http://127.0.0.1:3380"},5)
    if err!=nil{
        fmt.Println(err)
        os.Exit(1)
    }
    if err=rn.Init();err!=nil{
        fmt.Println(err)
        os.Exit(1)
    }
    defer rn.Close()
    remoteNotifyHandler := func(dirs []string, dfiles []string, cfiles []string) error {
        for _,f := range dfiles{
            if err:=rn.Delete(f);err!=nil{
                return err
            }
        }
        for _,f := range cfiles{
            if err:=rn.Add(f);err!=nil{
                return err
            }
        }
        return nil
    }
    printHandler := func(dirs []string, dfiles []string, cfiles []string) error {
        fmt.Println(cfiles)
        fmt.Println(dfiles)
        return nil
    }
    target := NewTarget("/mnt/hgfs/CODES_SHARE/get-router/watcher/a", "/mnt/hgfs/CODES_SHARE/get-router/watcher/b")
    target.NotifyHandlers = append(target.NotifyHandlers, localNotifyHandler,remoteNotifyHandler,printHandler)

    if err := target.init(); err != nil {
        fmt.Println(err)
        os.Exit(1)
    }
    if err := target.notify(); err != nil {
        fmt.Println(err)
        os.Exit(1)
    }
LOOP:
    for {
        select {
        case event := <-watcher.Events:
            if err := target.handle(event); err != nil {
                fmt.Println("handle error:", err)
                break LOOP
            }
            if err := target.notify(); err != nil {
                fmt.Println("notify error:", err)
                break LOOP
            }
        case err := <-watcher.Errors:
            fmt.Println("error:", err)
        }
    }
}
